<?php


class importexport_ctl_admin_import extends importexport_controller{

    const TTL = 600;//缓存时间
    const REDIS_DB = 1;
    /*
     *后台显示队列
     * */

    public function queue_import(){

        $params = array(
            'title'=>'导入任务队列',
            'use_buildin_recycle'=>true,
            'orderBy' => 'create_date desc',
            'base_filter'=>array('type'=>'import'),
        );
        //删除任务时，同时删除未执行的数据
        if(isset($_GET['action']) &&  ($_GET['action'] == 'dorecycle' )){
            if(!empty($_POST['task_id'])){
                $model = app::get('importexport')->model('task');
                $redis = new Redis();
                $redis->connect('127.0.0.1');
                $redis->select(1);
                foreach($_POST['task_id'] as $v){
                    $task = $model->dump($v);
                    $redis->del($task['key']);
                }
            }
        }
        $this->finder('importexport_mdl_task',$params);

    }

    /**
     * 下载模板文件
     */
    public function export_template(){

        //实例化导出数据类
        $dataObj = kernel::single('importexport_data_object',$_POST['mdl']);
        //实例化导出文件类型类
        $filetypeObj = kernel::single('importexport_type_'.$_POST['filetype']);

        $filetypeObj->set_queue_header($_POST['name'].'.'.$_POST['filetype']);

        $data = $dataObj->get_template($_POST['group_col']);

        $rs = $filetypeObj->fileHeader();
        $rs .= $filetypeObj->arrToExportType(array($data));
        $rs .= $filetypeObj->fileFoot();

        if( method_exists($filetypeObj, 'setBom') ){
            $bom = $filetypeObj->setBom();
            echo $bom;
        }
        echo $rs;
    }

    /*
     * 导入页面
     * */
    public function import_view(){
        $this->pagedata['check_policy'] = $this->check_policy();
        $this->pagedata['params'] = $_GET['_params'];
        //支持导出类型
        $this->pagedata['import_type'] = $this->import_support_filetype();
        $this->display('admin/import/import.html');
    }

    /*
     * 导入数据
     * */
    public function create_import(){
        #检查导入文件是否合法
        $this->check_import_file();

        #将导入文件上传到服务器
        $data = $this->push_file($_POST);

        if(array_key_exists('split',$data)){
            unset($data['split']);
            foreach($data as $datav){
                $queue_params = array(
                    'model'=>$_POST['mdl'],
                    'filetype' => $datav['filetype'],
                    'policy' => $this->queue_policy(),
                    'key'=> $datav['key'],
                );
                system_queue::instance()->publish('importexport_tasks_runimport', 'importexport_tasks_runimport', $queue_params);
                $task = app::get('importexport')->model('task')->create_task('import',$datav);

            }
        }else{

            $queue_params = array(
                'model'=>$_POST['mdl'],
                'filetype' => $data['filetype'],
                'policy' => $this->queue_policy(),
                'key'=> $data['key'],
            );

            system_queue::instance()->publish('importexport_tasks_runimport', 'importexport_tasks_runimport', $queue_params);
            $task = app::get('importexport')->model('task')->create_task('import',$data);
        }

        if($task) {
            $echoMsg = app::get('desktop')->_('上传成功,已加入队列');
            $this->import_message(true, $echoMsg);
        }else{
            $echoMsg = app::get('desktop')->_('加入队列失败');
            $this->import_message(true, $echoMsg);
        }
        #kernel::single('importexport_tasks_runimport')->exec($queue_params);
    }

    /**
     * 检查导入文件是否合法
     */
    private function check_import_file(){
        if( !$_FILES['import_file']['name'] ){
            $echoMsg =app::get('importexport')->_('未上传文件');
            $this->import_message(false,$echoMsg);
        }
        $filetype = strrchr($_FILES['import_file']['name'],'.');
        if( '.'.$_POST['filetype'] != $filetype )
        {
            $echoMsg =app::get('importexport')->_('请上传当前选中的文件类型');
            $this->import_message(false,$echoMsg);
        }
        $import_support_filetype = $this->import_support_filetype();
        if(!in_array($filetype,$import_support_filetype)){
            $echoMsg =app::get('importexport')->_('导入格式不支持');
            $this->import_message(false,$echoMsg);
        }
    }

    /**
     * 将导入文件上传到服务器
     * @param array $data
     */
    private function push_file($params){

        $redis = new Redis();
        $redis->connect('127.0.0.1');
        $redis->select(1);
        $filetype = substr(strrchr($_FILES['import_file']['name'],'.'),1);
        $tmpFileHandle = fopen( $_FILES['import_file']['tmp_name'],"r" );
        $filetypeObj = kernel::single('importexport_type_'.$filetype);//实例化导入文件类型类
        $dataObj = kernel::single('importexport_data_object',$params['mdl']);//实例化数据类
        $line = 0;
        $ftell = 0;
        while ( feof($tmpFileHandle) === false )
        {
            $contents = array();
            $msg = null;
            fseek($tmpFileHandle,$ftell);
            while ( $dataObj->check_continue($contents,$line) )
            {
                $ftell = ftell($tmpFileHandle);
                //从上传文件中以每行读取数据
                if ( !$filetypeObj->fgethandle($tmpFileHandle,$contents,$line) ) {
                    break;
                }

                //处理读取出的数据，格式化数据,将数据中的值对应到字段中
                $contents = $dataObj->pre_import_data($contents,$line);
                if ( $contents === false) {
                    $msg = app::get('importexport')->_('数据格式不正确');
                    $this->import_message(false,$msg);
                }
            }

            if($contents){
                $rs = serialize($contents);
                $data[] = $rs;
            }
        }


        $chunk = array_chunk($data,100);
        $key = $this->gen_key('import:');
        if(count($chunk) > 1){
            foreach($chunk as $k=>$data){

                foreach($data  as $value){
                    $redis->lPush($key.'-'.$k,$value);
                }
                $paramss[] = array(
                    'key'=>$key.'-'.$k,
                    'filetype'=>$filetype,
                    'name'=>'导入:'.$_FILES['import_file']['name'],
                    'status' => 0,
                    'app' => $params['app'],
                    'mdl' => $params['mdl'],
                    'filetype' => $params['filetype']
                );
            }
            $paramss['split'] = 1;
            return $paramss;
        }else{

            foreach($data  as $value){
                $redis->lPush($key,$value);
            }
            $params = array(
                'key'=>$key,
                'filetype'=>$filetype,
                'name'=>'导入:'.$_FILES['import_file']['name'],
                'status' => 0,
                'app' => $params['app'],
                'mdl' => $params['mdl'],
                'filetype' => $params['filetype']
            );
        }

        return $params;
    }


    public function queue_download(){
        $this->file_download();
        exit;
    }

    public function error_download(){
        $task_id = $_GET['task_id'];
        $model = app::get('importexport')->model('task');
        $task = $model->dump($task_id);
        $redis = new Redis();
        $redis->connect('127.0.0.1');
        $redis->select(1);

        header("Content-Type: application/octet-stream");
        if (preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT']) ) {
            header('Content-Disposition:  attachment; filename="' . $task['key'] . '"');
        } elseif (preg_match("/Firefox/", $_SERVER['HTTP_USER_AGENT'])) {
            header('Content-Disposition: attachment; filename*="utf8' .  $task['key'] . '"');
        } else {
            header('Content-Disposition: attachment; filename="' .  $task['key'] . '"');
        }//兼容各种浏览器。
        echo $redis->get($task['key'].'_error_message');exit;


    }

    public function restart_import(){
        $task_id = $_GET['task_id'];
        $model = app::get('importexport')->model('task');
        $task = $model->dump($task_id);

        $model->update(array('status'=>0),array('task_id'=>$task_id));

        $queue_params = array(
            'model'=>'b2c_mdl_goods',
            'filetype' => $task['filetype'],
            'policy' => $this->queue_policy(),
            'key'=> $task['key'],
        );
        system_queue::instance()->publish('importexport_tasks_runimport', 'importexport_tasks_runimport', $queue_params);
        $echoMsg = app::get('desktop')->_('已加入队列');
//        $this->import_message(true, $echoMsg);
        header("content-type:text/html; charset=utf-8");
        echo "<script>alert(\"".$echoMsg."\"); history.go(-1);location.reload();</script>";
        exit;
    }

}
